package com.common.aspect;

import cn.hutool.core.date.DateTime;
import com.common.annotation.AutoFill;

import com.common.constant.AutoFillConstant;

import com.common.constant.OperationType;
import com.common.holder.UserHolder;
import com.common.utils.IDUtils;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

@Component
@Aspect
@Slf4j
public class AutoFillAspect {
    @Autowired
    private IDUtils idUtils;
    @Pointcut("execution(* com..mapper..*.*(..)) && @annotation(com.common.annotation.AutoFill)")
    public void mapperPointCut(){}
    
    @Before("mapperPointCut()")
    public void timeAutoFill(JoinPoint joinPoint) throws NoSuchMethodException {
        log.info("开始进行时间填充");
        //获取当前被拦截的方法上的数据库字段
        MethodSignature signature = (MethodSignature)joinPoint.getSignature();//方法签名对象
        AutoFill annotation = signature.getMethod().getAnnotation(AutoFill.class);//获得方法名上的注解
        OperationType value = annotation.value();//获取操作类型
        
        //获取到当前被拦截的实体对象
        Object[] args = joinPoint.getArgs();
        if(args==null||args.length==0){
            return;
        }
        Object data = args[0];
        
        
        //准备赋值操作
        DateTime now = DateTime.now();
        
        if(value.equals(OperationType.INSERT)){
            Method id = data.getClass().getDeclaredMethod(AutoFillConstant.SET_ID, Long.class);
            Method createdTime = data.getClass().getDeclaredMethod(AutoFillConstant.SET_CREATE_TIME, DateTime.class);
            Method updatedTime = data.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, DateTime.class);
            try {
                id.invoke(data,idUtils.getId());
                createdTime.invoke(data,now);
                updatedTime.invoke(data,now);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }else if(value.equals(OperationType.UPDATE)){
            Method updatedTime = data.getClass().getDeclaredMethod(AutoFillConstant.SET_UPDATE_TIME, DateTime.class);
            try {
                updatedTime.invoke(data,now);
            } catch (IllegalAccessException | InvocationTargetException e) {
                throw new RuntimeException(e);
            }
        }
    }
}
